package com.example.dnfgamercommunitybackend.service.impl;

import com.example.dnfgamercommunitybackend.dao.FavoriteArticleDao;
import com.example.dnfgamercommunitybackend.entity.Article;
import com.example.dnfgamercommunitybackend.entity.FavoriteArticle;
import com.example.dnfgamercommunitybackend.entity.ResponseResult;
import com.example.dnfgamercommunitybackend.service.FavoriteArticleService;
import com.example.dnfgamercommunitybackend.util.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class FavoriteArticleServiceImpl implements FavoriteArticleService {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private FavoriteArticleDao favoriteArticleDao;
    @Override
    public String addFavoriteArticle(int articleId, String token) {
        int accountId = Integer.parseInt(jwtUtil.getUserIdFromToken(token));
        FavoriteArticle favoriteArticle = new FavoriteArticle();
        favoriteArticle.setId(articleId);
        favoriteArticle.setAccountId(accountId);
        if (!Objects.isNull(favoriteArticleDao.existCord(favoriteArticle))){
            return ResponseResult.failureStringResult("您已收藏此文章");
        }else {
            if (favoriteArticleDao.addFavoriteRecord(favoriteArticle) > 0){
                return ResponseResult.successStringResult("收藏成功");
            }
        }
        return ResponseResult.failureStringResult("收藏失败");
    }


    @Override
    public String getFavoriteListByUserId(String authorization) {
        List<Article> articles = favoriteArticleDao.getFavoriteListByUserId(Integer.parseInt(jwtUtil.getUserIdFromToken(authorization)));
        if (!articles.isEmpty()){
            return ResponseResult.successStringResult("获取收藏列表成功",articles);
        }
        return ResponseResult.failureStringResult(504,"收藏列表为空");

    }

    @Override
    public String cancelFavoriteArticle(int id, String authorization) {
        //获取用户id
        int userId = Integer.parseInt(jwtUtil.getUserIdFromToken(authorization));
        FavoriteArticle favoriteArticle = new FavoriteArticle();
        favoriteArticle.setId(id);
        favoriteArticle.setAccountId(userId);
        if (favoriteArticleDao.cancelFavoriteArticle(favoriteArticle) > 0){
            return ResponseResult.successStringResult("取消收藏成功");
        }
        return ResponseResult.failureStringResult("取消成功失败，id不存在");
    }
}
